﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using Core.Model;
using Core.Services;
using Infrastructure.Repositories;
using UI.Models.Account;

namespace UI.Controllers
{
    public class AccountController : Controller
    {
        private readonly IAccountService _accountService;

        public AccountController()
            : this(new AccountService(new AccountRepository()))
        {

        }

        public AccountController(IAccountService accountService)
        {
            if (accountService == null) throw new ArgumentNullException("accountService");
            _accountService = accountService;
        }

        

        public ActionResult Show()
        {
            string userId = HttpContext.User.Identity.Name;

            var account = _accountService.RetrieveAccount(userId);

            if (account != null)
            {
                UI.Models.Account.Show showAccount = new AccountMapper().From(account);
                return View(showAccount);
            }

            return View("NotFound");
        }

        [AllowAnonymous]
        public ActionResult Create()
        {
            return View("Create", new Account());
        }

        [AllowAnonymous]
        public ActionResult Logon()
        {

            string returnUrl = Request.QueryString != null ? Request.QueryString["ReturnUrl"] : null;
            var model = new Logon { ReturnUrl = returnUrl };
            return View("logon", model);

        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Logon(Logon logon)
        {
            if (ModelState.IsValid)
            {
                var isAuthenticated = _accountService.ValidateUser(logon.UserId, logon.Password);
                if (isAuthenticated)
                {
                    var account = _accountService.RetrieveAccount(logon.UserId);

                    if (account != null)
                    {
                        FormsAuthentication.SetAuthCookie(logon.UserId, false);
                        return Redirect(logon.ReturnUrl);
                    }
                    
                }
            }
            return View("logon", logon);
        }
    }
}
